package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.bean.OrderDetail;
import com.itheima.reggie.bean.Orders;
import com.itheima.reggie.bean.ShoppingCart;
import com.itheima.reggie.common.BeasContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 * User: 许志民
 * Date: 2021-11-28
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info("订单数据{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    ///userPage?page=1&pageSize=5
    @GetMapping("/userPage")
    public R userPage(Integer page,Integer pageSize){
        IPage<Orders> iPage = new Page<>(page,pageSize);
        IPage<Orders> page1 = orderService.page(iPage);
        OrdersDto ordersDto = new OrdersDto();
        List<OrdersDto> ordersDtos = JSON.parseArray(JSON.toJSONString(page1.getRecords()), OrdersDto.class);

        ordersDtos = ordersDtos.stream().map((item) ->{

            LambdaQueryWrapper<OrderDetail> warpper = new LambdaQueryWrapper<>();
            warpper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> list = orderDetailService.list(warpper);
            item.setOrderDetails(list);
            return item;
        }).collect(Collectors.toList());
        Page<OrdersDto> ordersDtoPage = new Page<>();
        ordersDtoPage.setRecords(ordersDtos);
        ordersDtoPage.setTotal(page1.getTotal());
        ordersDtoPage.setSize(page1.getSize());
        ordersDtoPage.setCurrent(page1.getCurrent());
        ordersDtoPage.setMaxLimit(page1.maxLimit());
        return R.success(ordersDtoPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R again(@RequestBody Orders orders){
        //先判断购物车中是否有菜品或者套餐，如果有则全部清除
        Long userId = BeasContext.getCurrentId();
        LambdaUpdateWrapper<ShoppingCart> shoppingCartLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        shoppingCartLambdaUpdateWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(shoppingCartLambdaUpdateWrapper);
        log.info("接收到参数为{}",orders.getId());
        LambdaQueryWrapper<OrderDetail> wapper = new LambdaQueryWrapper<>();
        wapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list = orderDetailService.list(wapper);
        List<ShoppingCart> shoppingCarts = list.stream().map(item ->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setName(item.getName());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setImage(item.getImage());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("添加成功");
    }

    //order/page?page=1&pageSize=10
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number, String statrTime, String endTime ){
        IPage<Orders> iPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wapper = new LambdaQueryWrapper<>();
        if(number != null){
            wapper.like(Orders::getNumber,number);
        }
        if(statrTime != null && statrTime != "" && endTime != null && endTime != ""){
            wapper.between(Orders::getOrderTime,statrTime,endTime);
        }


        IPage<Orders> page1 = orderService.page(iPage, wapper);

        return R.success(page1);
    }

    @PutMapping
    public R updateStatus(@RequestBody Orders orders){
        if(orders == null){
            return R.error("参数异常");
        }
        boolean falg = orderService.updateStatus(orders);

        return falg ? R.success("修改成功") : R.error("修改失败");
    }
}
